import { ref, onMounted } from 'vue'
import { regionOptimizedApi } from '@/api/regionOptimized'
import { ElMessage } from 'element-plus'

/**
 * 地区数据加载Hook - 优化版本
 * 解决地区数据加载超时问题
 */
export function useRegionData() {
  const regionData = ref<
    Array<{
      id: number
      name: string
      cities?: Array<{
        id: number
        name: string
        districts?: Array<{
          id: number
          name: string
        }>
      }>
    }>
  >([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  /**
   * 加载地区数据
   */
  const loadRegions = async () => {
    loading.value = true
    error.value = null

    try {
      const data = await regionOptimizedApi.getProvinces()
      regionData.value = data

      if (data.length === 0) {
        ElMessage.warning('地区数据加载为空')
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '地区数据加载失败'
      console.error('地区数据加载失败:', err)
      ElMessage.error('地区数据加载失败')
    } finally {
      loading.value = false
    }
  }

  /**
   * 强制刷新地区数据
   */
  const refreshRegions = async () => {
    // 清除本地缓存
    localStorage.removeItem('region_data_cache')
    localStorage.removeItem('region_data_cache_expiry')

    await loadRegions()
  }

  /**
   * 获取指定层级的地区数据
   */
  const getRegionsByLevel = (level: number) => {
    if (level === 1) {
      return regionData.value // 省份
    } else if (level === 2) {
      // 城市 - 扁平化所有城市
      const cities: any[] = []
      regionData.value.forEach(province => {
        if (province.cities) {
          cities.push(...province.cities)
        }
      })
      return cities
    } else if (level === 3) {
      // 区县 - 扁平化所有区县
      const districts: any[] = []
      regionData.value.forEach(province => {
        if (province.cities) {
          province.cities?.forEach(city => {
            if (city.districts) {
              districts.push(...city.districts)
            }
          })
        }
      })
      return districts
    }
    return []
  }

  /**
   * 根据ID获取地区名称
   */
  const getRegionName = (id: number): string => {
    const findRegion = (items: any[]): string => {
      for (const item of items) {
        if (item.id === id) {
          return item.name
        }

        if (item.cities) {
          for (const city of item.cities) {
            if (city.id === id) {
              return city.name
            }

            if (city.districts) {
              for (const district of city.districts) {
                if (district.id === id) {
                  return district.name
                }
              }
            }
          }
        }
      }
      return ''
    }

    return findRegion(regionData.value)
  }

  /**
   * 根据父ID获取子地区
   */
  const getChildrenByParentId = (parentId: number) => {
    const findChildren = (items: any[]): any[] => {
      for (const item of items) {
        if (item.id === parentId) {
          return item.cities || []
        }

        if (item.cities) {
          for (const city of item.cities) {
            if (city.id === parentId) {
              return city.districts || []
            }
          }
        }
      }
      return []
    }

    return findChildren(regionData.value)
  }

  // 组件挂载时自动加载
  onMounted(() => {
    loadRegions()
  })

  return {
    regionData,
    loading,
    error,
    loadRegions,
    refreshRegions,
    getRegionsByLevel,
    getRegionName,
    getChildrenByParentId,
  }
}
